// 将路由嵌套的数据拉平 深度优先遍历
export const flatMenuData = (routers) => {
  const res = [];
  routers.forEach((router) => {
    const { children, ...rest } = router;
    res.push(rest);
    if (children && children.length) {
      res.push(...flatMenuData(children));
    }
  });
  return res;
};

// 根据路由 path 查找当前路由所在的 children 数组
export const getChildrenMenuDataByPath = (routers, path) => {
  let res = [];
  for (let i = 0; i < routers.length; i++) {
    const { children, ...rest } = routers[i];
    if (rest.path === path) {
      res = [...routers];
      break;
    } else if (children && children.length) {
      res = getChildrenMenuDataByPath(children, path);
      if (res.length) {
        break;
      }
    }
  }
  return res;
};

// 根据路由 path 查找当前路由所在的 root 节点
export const getRootMenuDataByPath = (routers, path) => {
  let result = null;
  const childrenHasPath = (childrenRouters, path) => {
    return childrenRouters.some((item) => {
      const { children, ...rest } = item;
      if (rest.path === path) {
        return true;
      } else if (children && children.length) {
        return childrenHasPath(children, path);
      }
      return false;
    });
  };
  for (let i = 0; i < routers.length; i++) {
    const routerItem = routers[i];
    const { children, ...rest } = routerItem;
    if (rest.path === path) {
      result = routerItem;
      break;
    } else if (children && children.length && childrenHasPath(children, path)) {
      result = routerItem;
      break;
    }
  }
  return result;
};

/**
 * 转换 asyncRouters 数据
 * @param asyncRouters
 * @description 将本地的 asyncRouters 数据转换成 vue-router 可以使用的数据
 */
export const transformAsyncMenuData = (asyncRouters) => {
  const result = [];
  const loopRouter = (routers) => {
    routers.forEach((routerItem) => {
      const { children, path, component, ...rest } = routerItem;
      if (component) {
        result.push({
          ...rest,
          path,
          component
        });
      }
      if (children && children.length) {
        loopRouter(children);
      }
    });
  };
  loopRouter(asyncRouters);
  return result;
};
